<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="mode==='add'?'新增终端':'编辑终端'"
    :close-on-click-modal="false"
    width="750px"
    top="10vh"
    @close="close"
  >
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="110px" size="small">
      <el-form-item label="所属店铺：" prop="shopId">
        <el-select v-model="form.shopId" filterable clearable placeholder="可通过名称搜索">
          <el-option
            v-for="item in shopOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="终端名称：" prop="deviceName">
        <el-input v-model="form.deviceName" maxlength="20" show-word-limit placeholder="请输入" />
      </el-form-item>

      <el-form-item v-if="form.kdDeviceNo" label="终端编号：">
        {{ form.kdDeviceNo }}
      </el-form-item>

      <el-form-item label="第三方编号：" prop="outDeviceNo">
        <el-input v-model.trim="form.outDeviceNo" maxlength="50" show-word-limit placeholder="请输入" />
      </el-form-item>

      <el-form-item label="秘钥：" prop="secretKey">
        <el-input
          v-model.trim="form.secretKey"
          :autosize="{ minRows: 3, maxRows: 6}"
          maxlength="200"
          show-word-limit
          type="textarea"
          placeholder="请输入"
        />
      </el-form-item>

      <el-form-item label="备注：" prop="description">
        <el-input v-model="form.description" maxlength="30" show-word-limit placeholder="说明备注" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" round @click="hide">取 消</el-button>
      <el-button size="small" round type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addDevice, editDevice } from '@/api/mch/equipment'
import { allShopList } from '@/api/mch/shop'
import { validEngNum } from '@/utils/validate'

export default {
  data() {
    /**
     * 表单校验方法
     */
    // 终端编号
    const validateOutDeviceNo = (rule, value, callback) => {
      if (this.$isNull(value)) {
        callback()
      } else if (!validEngNum(value, 1, 50)) {
        callback(new Error('仅支持数字，大小写字母'))
      } else {
        callback()
      }
    }
    return {
      // 校验字段相关
      rules: {
        shopId: [
          {
            required: true,
            message: '请选择店铺',
            trigger: ['change', 'blur']
          }
        ],
        secretKey: [
          {
            required: false,
            message: '请输入秘钥',
            trigger: ['change', 'blur']
          },
          { min: 10, max: 200, message: '长度大于等于 10 个字符', trigger: ['blur', 'change'] }
        ],
        deviceName: [
          {
            required: true,
            message: '请输入终端名称',
            trigger: ['blur', 'change']
          }
        ],
        outDeviceNo: [
          {
            validator: validateOutDeviceNo,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      title: null,
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: false,
      loading: false,
      // 数据
      shopOptions: [],
      mode: 'add',
      form: {
        shopId: '',
        deviceName: '',
        outDeviceNo: '',
        secretKey: '',
        description: ''
      }
    }
  },
  computed: {},
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {

  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    // 弹框相关
    open({ mode = 'add', row = null }) {
      this.getAllShopOptions()
      this.mode = mode
      if (mode === 'edit') this.form = Object.assign({}, row)
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    close() {
      this.form = {
        shopId: '',
        deviceName: '',
        outDeviceNo: '',
        secretKey: '',
        description: ''
      }
      this.$refs.form.resetFields()
      this.loading = false
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.mode === 'add' ? this.add() : this.edit()
        }
      })
    },

    /**
     * 数据组
     */
    // 获取所有门店
    getAllShopOptions() {
      const params = {
        businessId: this.$route.query.mchId
      }
      this.loading = true
      allShopList({ params }).then(res => {
        this.shopOptions = res.data || []
      }).finally(() => {
        this.loading = false
      })
    },

    /**
     * 按钮组
     */
    // 新增
    add() {
      this.loading = true
      const params = Object.assign({}, this.form)
      params.businessId = this.$route.query.mchId
      addDevice({ data: params }).then(() => {
        this.$root.$emit('refreshMchEquipmentDeviceList')
        this.$notify({
          title: '成功',
          message: '新增成功',
          type: 'success',
          duration: 2000,
          offset: 40
        })
        this.hide()
      }).finally(() => {
        this.loading = false
      })
    },

    // 编辑
    edit() {
      this.loading = true
      const params = Object.assign({}, this.form)
      editDevice({ data: params }).then(() => {
        this.$root.$emit('refreshMchEquipmentDeviceList')
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000,
          offset: 40
        })
        this.resolve && this.resolve()
        this.hide()
      }).finally(() => {
        this.loading = false
      })
    }
    /**
     * 状态组
     */
    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.el-select {
  width: 100%;
}

.el-checkbox {
  width: 120px;
}
</style>
